package com.zhb.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;

public class XMLUtilities {

    public static String marshall(Object data, String encoding) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            JAXBContext jc = JAXBContext.newInstance(data.getClass());
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(data, out);
            //转码
            return out.toString(encoding);
        } catch (Exception ignored) {
            return "";
        }
    }

    public static <T> T unMarshall(String xml, Class<T> clazz) {
        try {
            JAXBContext jc = JAXBContext.newInstance(clazz);
            final Unmarshaller unmarshaller = jc.createUnmarshaller();
            T data = (T)unmarshaller.unmarshal(new StringReader(xml));
            return(data);
        } catch (Exception ignored) {}
        return null;
    }

}